<template>
  <view class="exercise-container">
    <!-- 页面标题 -->
    <view class="page-title">数学练习题</view>

    <!-- 选择区域 -->
    <view class="selection-area" v-if="!isStarted">
      <view class="form-item">
        <text class="form-label">选择年级</text>
        <picker @change="onGradeChange" :range="grades">
          <view class="picker">
            {{ selectedGrade || '请选择年级' }}
          </view>
        </picker>
      </view>

      <view class="form-item">
        <text class="form-label">选择题目类型</text>
        <view class="type-selector">
          <view
            class="type-item"
            :class="{ active: selectedType === 'addition' }"
            @click="selectedType = 'addition'"
          >
            加法
          </view>
          <view
            class="type-item"
            :class="{ active: selectedType === 'subtraction' }"
            @click="selectedType = 'subtraction'"
          >
            减法
          </view>
          <view
            class="type-item"
            :class="{ active: selectedType === 'mixed' }"
            @click="selectedType = 'mixed'"
          >
            混合运算
          </view>
        </view>
      </view>

      <button class="start-btn" @click="startExercise" :disabled="!selectedGrade">开始练习</button>
    </view>

    <!-- 答题区域 -->
    <view class="question-area" v-else-if="!isFinished">
      <view class="question-info">
        <text>第 {{ currentQuestionIndex + 1 }} / {{ questions.length }} 题</text>
        <text>用时: {{ timeUsed }}s</text>
      </view>

      <view class="question-content">
        <text class="question-text">{{ currentQuestion.question }}</text>
      </view>

      <view class="options">
        <view
          class="option-item"
          :class="{
            selected: currentQuestion.selectedOption === index,
            correct: isAnswered && currentQuestion.correctOption === index,
            wrong:
              isAnswered &&
              currentQuestion.selectedOption === index &&
              currentQuestion.correctOption !== index,
          }"
          v-for="(option, index) in currentQuestion.options"
          :key="index"
          @click="selectOption(index)"
          :disabled="isAnswered"
        >
          {{ option }}
        </view>
      </view>

      <button class="next-btn" @click="nextQuestion" :disabled="!isAnswered">
        {{ currentQuestionIndex === questions.length - 1 ? '完成' : '下一题' }}
      </button>
    </view>

    <!-- 结果区域 -->
    <view class="result-area" v-else>
      <view class="result-icon">
        <image src="@/static/images/success.png" mode="aspectFit"></image>
      </view>
      <view class="result-title">练习完成!</view>
      <view class="result-stats">
        <view class="stat-item">
          <text class="stat-label">正确率</text>
          <text class="stat-value">{{ accuracy }}%</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">用时</text>
          <text class="stat-value">{{ timeUsed }}秒</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">答对</text>
          <text class="stat-value">{{ correctCount }}题</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">答错</text>
          <text class="stat-value">{{ wrongCount }}题</text>
        </view>
      </view>

      <view class="result-actions">
        <button class="retry-btn" @click="startExercise">重新练习</button>
        <button class="view-error-btn" @click="viewErrorQuestions" :disabled="wrongCount === 0">
          查看错题
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMemberStore } from '@/stores'
import { saveExerciseResultAPI } from '@/services/exercise'
import { saveErrorQuestion, clearErrorQuestions } from '@/utils/localStorage'

type Question = {
  question: string
  options: string[]
  correctOption: number
  selectedOption?: number
  isCorrect?: boolean
}

// 年级选项
const grades = ['一年级', '二年级']
// 选中的年级
const selectedGrade = ref<string>('')
// 选中的题目类型
const selectedType = ref<string>('addition') // addition, subtraction, mixed
// 是否开始练习
const isStarted = ref<boolean>(false)
// 是否完成练习
const isFinished = ref<boolean>(false)
// 问题列表
const questions = ref<Question[]>([])
// 当前问题索引
const currentQuestionIndex = ref<number>(0)
// 是否已回答当前问题
const isAnswered = ref<boolean>(false)
// 用时
const timeUsed = ref<number>(0)
// 计时器
let timer: number | null = null
// 正确数量
const correctCount = ref<number>(0)
// 错误数量
const wrongCount = ref<number>(0)
// 正确率
const accuracy = computed(() => {
  return Math.round((correctCount.value / questions.value.length) * 100)
})
// 当前问题
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

// 年级选择变化
const onGradeChange = (e: any) => {
  selectedGrade.value = grades[e.detail.value]
}

// 生成随机数
const getRandomNumber = (max: number) => {
  return Math.floor(Math.random() * max) + 1
}

// 生成题目
const generateQuestions = () => {
  const newQuestions: Question[] = []
  for (let i = 0; i < 10; i++) {
    let a: number, b: number, operator: string, result: number
    let questionText: string

    if (selectedType.value === 'addition') {
      a = getRandomNumber(10)
      b = getRandomNumber(10 - a)
      operator = '+'
      result = a + b
      questionText = `${a} ${operator} ${b} = ?`
    } else if (selectedType.value === 'subtraction') {
      a = getRandomNumber(10)
      b = getRandomNumber(a)
      operator = '-'
      result = a - b
      questionText = `${a} ${operator} ${b} = ?`
    } else {
      // 混合运算
      if (Math.random() > 0.5) {
        a = getRandomNumber(10)
        b = getRandomNumber(10 - a)
        operator = '+'
        result = a + b
        questionText = `${a} ${operator} ${b} = ?`
      } else {
        a = getRandomNumber(10)
        b = getRandomNumber(a)
        operator = '-'
        result = a - b
        questionText = `${a} ${operator} ${b} = ?`
      }
    }

    // 生成选项
    const options = [result]
    while (options.length < 4) {
      let randomOption = result + getRandomNumber(5) - 2
      // 确保选项在0-20之间且不重复
      if (randomOption >= 0 && randomOption <= 20 && !options.includes(randomOption)) {
        options.push(randomOption)
      }
    }

    // 打乱选项顺序
    options.sort(() => Math.random() - 0.5)

    // 找到正确选项的索引
    const correctOption = options.indexOf(result)

    newQuestions.push({
      question: questionText,
      options: options.map((option) => option.toString()),
      correctOption,
    })
  }
  return newQuestions
}

// 开始练习
const startExercise = () => {
  if (!selectedGrade.value) {
    uni.showToast({
      title: '请选择年级',
      icon: 'none',
    })
    return
  }

  questions.value = generateQuestions()
  currentQuestionIndex.value = 0
  isStarted.value = true
  isFinished.value = false
  correctCount.value = 0
  wrongCount.value = 0
  timeUsed.value = 0
  isAnswered.value = false

  // 开始计时
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    timeUsed.value++
  }, 1000) as unknown as number
}

// 选择选项
const selectOption = (index: number) => {
  currentQuestion.value.selectedOption = index
  isAnswered.value = true

  // 检查是否正确
  if (index === currentQuestion.value.correctOption) {
    currentQuestion.value.isCorrect = true
    correctCount.value++
  } else {
    currentQuestion.value.isCorrect = false
    wrongCount.value++
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value === questions.value.length - 1) {
    // 完成练习
    finishExercise()
  } else {
    currentQuestionIndex.value++
    isAnswered.value = false
  }
}

// 完成练习
const finishExercise = () => {
  isFinished.value = true
  clearInterval(timer as unknown as number)
  timer = null

  // 保存错题到本地
  const wrongQuestions = questions.value.filter((q) => q.selectedOption !== q.correctOption)
  wrongQuestions.forEach((question) => {
    saveErrorQuestion({
      question: question.question,
      options: question.options,
      correctOption: question.correctOption,
      selectedOption: question.selectedOption,
      grade: selectedGrade.value,
      type: selectedType.value,
    })
  })

  // 保存练习结果（如果仍需保存到后台）
  saveExerciseResultAPI({
    grade: selectedGrade.value,
    type: selectedType.value,
    id: '',
    userId: useMemberStore().profile?.userId || null,
    createTime: new Date().toISOString(),
    correctCount: correctCount.value,
    totalCount: questions.value.length,
    timeUsed: timeUsed.value,
  })
}

// 查看错题
const viewErrorQuestions = () => {
  // 这里可以跳转到错题本页面
  uni.navigateTo({
    url: '/pages/exercise/errorQuestions',
  })
}

// 页面卸载时清除计时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer as unknown as number)
    timer = null
  }
})

onMounted(() => {
  // 清空错题
  clearErrorQuestions()
})
</script>

<style lang="scss">
.exercise-container {
  padding: 30rpx;
  box-sizing: border-box;
  min-height: 100vh;
  background-color: #f8f9fa;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
  color: #333;
}

.selection-area {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 10rpx;
  color: #333;
}

.picker {
  width: 100%;
  height: 70rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 70rpx;
  color: #666;
}

.type-selector {
  display: flex;
  gap: 20rpx;
}

.type-item {
  flex: 1;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
  line-height: 70rpx;
  color: #666;
}

.type-item.active {
  background-color: #409eff;
  color: #fff;
}

.start-btn {
  width: 100%;
  height: 80rpx;
  background-color: #409eff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  margin-top: 20rpx;
}

.question-area {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.question-info {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.question-content {
  margin-bottom: 40rpx;
  text-align: center;
}

.question-text {
  font-size: 40rpx;
  color: #333;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.option-item {
  height: 90rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 32rpx;
  text-align: center;
  line-height: 90rpx;
  color: #333;
}

.option-item.selected {
  border-color: #409eff;
  background-color: #e6f7ff;
}

.option-item.correct {
  border-color: #52c41a;
  background-color: #f6ffed;
  color: #52c41a;
}

.option-item.wrong {
  border-color: #f5222d;
  background-color: #fff2f0;
  color: #f5222d;
}

.next-btn {
  width: 100%;
  height: 80rpx;
  background-color: #409eff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
}

.result-area {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
}

.result-icon image {
  width: 100%;
  height: 100%;
}

.result-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 40rpx;
}

.result-stats {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 40rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20rpx;
  width: 45%;
}

.stat-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.result-actions {
  display: flex;
  gap: 20rpx;
  width: 100%;
}

.retry-btn,
.view-error-btn {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  border-radius: 40rpx;
}

.retry-btn {
  background-color: #409eff;
  color: #fff;
}

.view-error-btn {
  background-color: #f5f5f5;
  color: #666;
}

// 适配不同屏幕尺寸
@media screen and (max-width: 320px) {
  .question-text {
    font-size: 36rpx;
  }
  .option-item {
    height: 80rpx;
    font-size: 28rpx;
    line-height: 80rpx;
  }
  .stat-item {
    width: 100%;
  }
}

@media screen and (min-width: 768px) {
  .exercise-container {
    max-width: 600rpx;
    margin: 0 auto;
  }
}
</style>
